import request from './lib/request'
import cheerio from 'cheerio'
import model from './model'
import path from 'path'
import fs from 'fs'

// 获取url中的参数
function getQueryString(url, name) {
  var reg = new RegExp('(\\?|&)' + name + '=([^&]*)(&|$)', 'i') // 匹配目标参数
  var result = url.substr(1).match(reg) // 对querystring匹配目标参数
  if (result != null) {
    return decodeURIComponent(result[2])
  } else {
    return null
  }
}

async function down(url, id) {
  const params = url.match(/(\?|&)\S*/g)

  if (params) {
    const file = await request({
      methods: 'get',
      url: '/manage/apUser/downloadImage' + params[0],
      responseType: 'arraybuffer'
    })
    const fileName = path.basename(getQueryString(url, 'fileName'))
    const fileDir = process.config.filePrefix + '/' + id + '-' + fileName

    fs.writeFileSync(process.config.savePath + fileDir, file)
    return fileDir
  }
}

async function details(id) {
  const response = await request({
    methods: 'get',
    url: '/manage/apUser/toDetail',
    params: {
      id
    }
  })

  var $ = cheerio.load(response)

  const idCardImage = await down($('#certificate1_img').attr('src'), id)
  const drivingLicenceImage = await down($('#certificate2_img').attr('src'), id)

  var data = {
    id: id,
    userName: $('#loginName').val(),
    idCardName: $('#userName').val(),
    idCardNo: $('#credentials').val(),
    idCardBirthday: $('[name="birthday"]').val(),
    idCardNational: $('[name="nation"]').val(),
    idCardHouseholdRegister: $('[name="householdAddress"]').val(),
    drivingLicenceNo: $('[name="drivingLicence"]').val(),
    drivingLicenceEndTime: $('[name="effective"]').val(),
    drivingLicenceReceiveAddress: $('[name="driveAddress"]').val(),
    drivingLicenceFileNo: $('[name="driveArchivesNumber"]').val(),
    idCardImage,
    drivingLicenceImage
  }
  await model.update(data)
}

export default details
